package com.xjscrm.console.service.customer.corp;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.CorpApplication;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.ww.WwApiUtil;
import com.xjscrm.common.utils.ww.dto.WwTagGetResultDTO;
import com.xjscrm.console.dto.corp.WwCorpDTO;
import com.xjscrm.console.entity.WwCorp;
import com.xjscrm.console.mapper.WwCorpMapper;
import com.xjscrm.console.mapper.WwDeviceMapper;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.QueryParam;
import com.xjscrm.console.service.common.corpapplication.CorpApplicationService;
import com.xjscrm.console.vo.WwCorpVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author mingyang.chen create in 2024/5/6 18:50
 */
@Service
@Slf4j
public class WwCorpService {

    @Value("${ww.domain}")
    private String wwCallbackDomain;

    @Resource
    private WwCorpMapper wwCorpMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private CorpApplicationService corpApplicationService;


    public int deleteByPrimaryKey(Long id) {
        return wwCorpMapper.deleteByPrimaryKey(id);
    }


    public int insertSelective(WwCorp record) {
        return wwCorpMapper.insertSelective(record);
    }


    public WwCorp selectByPrimaryKey(Long id) {
        return wwCorpMapper.selectByPrimaryKey(id);
    }


    public int updateByPrimaryKeySelective(WwCorp record) {
        return wwCorpMapper.updateByPrimaryKeySelective(record);
    }

    public Object page(@MerId Long merId, QueryParam source) {
        Page<WwCorp> page = new Page<>(source.getCurrent(), source.getSize());
        source.convert(page);
        WwCorp param = new WwCorp();
        param.setMerId(merId);
        List<WwCorp> circleTaskList = wwCorpMapper.selectPage(page, param);

        List<WwCorpVO> resultRecord = new ArrayList<>();
        for (WwCorp circleTask : circleTaskList) {
            WwCorpVO wwCorpVO = new WwCorpVO();
            BeanUtils.copyProperties(circleTask, wwCorpVO);

            //查询是否已经授权服务商代理的接口
            wwCorpVO.setAuthCorpId(null);
            wwCorpVO.setAuthStatus(0);
            CorpApplication corpApplication = corpApplicationService.getByCorpId(circleTask.getCorpId());
            if(corpApplication != null){
                String authCorpId = corpApplication.getAuthCorpId();
                if(StringUtils.isNotBlank(authCorpId)){
                    wwCorpVO.setAuthCorpId(authCorpId);
                    wwCorpVO.setAuthStatus(1);
                }
                wwCorpVO.setStatus(corpApplication.getStatus());
                wwCorpVO.setCorpNameSimple(corpApplication.getCorpNameSimple());
            }

            resultRecord.add(
                    wwCorpVO
            );
        }
        return new Page<WwCorpVO>(page.getCurrent(), page.getSize(), page.getTotal()).setRecords(resultRecord);
    }

    public WwCorpVO get(@MerId Long merId, Long id) {
        WwCorp wwCorp = wwCorpMapper.selectByPrimaryKey(id);
        if (Objects.isNull(wwCorp)) {
            throw new BusinessException("企业不存在");
        }
        WwCorpVO wwCorpVO = new WwCorpVO();
        BeanUtils.copyProperties(wwCorp, wwCorpVO);
        return wwCorpVO;
    }

    public WwCorpVO getAndCheck(@MerId Long merId, Long id) {
        WwCorp wwCorp = wwCorpMapper.selectByCorpId(id, merId);
        if (Objects.isNull(wwCorp)) {
            throw new BusinessException("企业不存在");
        }
//        if (StringUtils.isAnyBlank(wwCorp.getEntId(), wwCorp.getEntSecret())) {
//            throw new BusinessException("企业配置信息错误");
//        }
        WwCorpVO wwCorpVO = new WwCorpVO();
        BeanUtils.copyProperties(wwCorp, wwCorpVO);
        return wwCorpVO;
    }

    public Boolean check(@MerId Long merId) {
        List<WwCorp> wwCorps = wwCorpMapper.selectByMerId(merId);
        if (ObjectUtils.isEmpty(wwCorps)) {
            return false;
        }

        return wwCorps.stream().anyMatch(item -> {
            CorpApplication corpApplication = corpApplicationService.getByCorpId(item.getCorpId());
            if (Objects.isNull(corpApplication)) {
                return false;
            }
            Integer status = corpApplication.getStatus();
            return !Objects.equals(status, 1);
        });
    }

    public Object edit(@MerId Long merId, WwCorpDTO source) {
//        String entId = source.getEntId();
//        String entSecret = source.getEntSecret();
//        try {
//            WwApiUtil.forceGetAccessToken(entId, entSecret);
//        } catch (Exception e) {
//            log.error("获取令牌失败", e);
//            throw new BusinessException("secret或企业id错误,请检查配置");
//        }
//        WwCorp update = new WwCorp();
//        update.setId(source.getId());
//        update.setEntId(entId);
//        update.setEntSecret(entSecret);
//        update.setEntToken(source.getEntToken());
//        update.setEntAesKey(source.getEntAesKey());
//        update.setRemark(source.getRemark());
//        update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
//        this.updateByPrimaryKeySelective(update);

        WwCorp wwCorp = this.wwCorpMapper.selectByPrimaryKey(source.getId());
        if (Objects.isNull(wwCorp)) {
            throw new BusinessException("企业信息不存在");
        }

        CorpApplication corpApplication = corpApplicationService.getByCorpId(wwCorp.getCorpId());
        if (Objects.isNull(corpApplication)) {
            throw new BusinessException("企业信息不存在");
        }
        CorpApplication update = new CorpApplication();
        update.setId(corpApplication.getId());
        update.setCorpNameSimple(source.getCorpNameSimple());
        corpApplicationService.update(update);
        return true;
    }

    public Object remove(@MerId Long merId, Long id) {
        this.wwCorpMapper.deleteByPrimaryKey(id);
        return true;
    }

    public Object add(@MerId Long merId, WwCorpDTO source) {
        WwCorp add = new WwCorp();
        add.setId(IdUtil.getSnowflakeNextId());
        add.setMerId(merId);
        add.setName(source.getName());
        add.setCorpId(source.getCorpId());
        add.setEntId(source.getEntId());
        add.setEntSecret(source.getEntSecret());
        add.setEntToken(source.getEntToken());
        add.setEntAesKey(source.getEntAesKey());
        add.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
        add.setCreateTime((int) (System.currentTimeMillis() / 1000L));
        this.insertSelective(add);
        return true;
    }


    public Object getDropDown(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        List<Map> mapList = new ArrayList<>();
        List<WwCorp> wwCorpList = wwCorpMapper.getByMerId(baseDto.getMerId());
        if (wwCorpList != null && !wwCorpList.isEmpty()) {
            for (WwCorp wwCorp : wwCorpList) {
                try {
                    Integer num = wwDeviceMapper.getCountByCorpId(wwCorp.getCorpId(), wwCorp.getMerId());
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("label", wwCorp.getName());
                    map.put("value", wwCorp.getCorpId());
                    map.put("deviceNum", num);
                    mapList.add(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return mapList;
    }

    public Object callbackUrl(@MerId Long merId, Long id) {
        WwCorp wwCorp = wwCorpMapper.selectByPrimaryKey(id);
        if (Objects.isNull(wwCorp)) {
            throw new BusinessException("企业不存在");
        }
        if (StringUtils.isBlank(wwCorp.getEntId())) {
            throw new BusinessException("请先配置企业id在查看回调地址!");
        }
        return wwCallbackDomain + "/" + merId + "/" + wwCorp.getEntId();
    }

    public Object checkAuth(@MerId Long merId, Long id) {
        WwCorp wwCorp = wwCorpMapper.selectByPrimaryKey(id);
        if (Objects.isNull(wwCorp)) {
            throw new BusinessException("企业不存在");
        }
        CorpApplication corpApplication = corpApplicationService.getByCorpId(wwCorp.getCorpId());
        if (Objects.isNull(corpApplication)) {
            throw new BusinessException("企业未授权");
        }
        String appAccessToken = WwApiUtil.getAppAccessToken(corpApplication.getAuthCorpId(), corpApplication.getPermanentCode());
        if (StringUtils.isBlank(appAccessToken)) {
            throw new BusinessException("企业授权信息错误");
        }
        try {
            WwTagGetResultDTO wwTagGetResultDTO = WwApiUtil.listTag(appAccessToken, null, null);
            CorpApplication update = new CorpApplication();
            update.setId(corpApplication.getId());
            update.setMerId(merId);
            update.setStatus(1);
            update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));

            corpApplicationService.update(update);
        } catch (Exception e) {
            throw new BusinessException("企微授权信息错误, 请检查配置!");
        }
        return true;
    }
}
